//
//  NewsViewController.m
//  WWLNetease
//
//  Created by dllo on 15/12/21.
//  Copyright © 2015年 Echo.Jobs. All rights reserved.
//

#import "NewsViewController.h"
#import "WZXButtonViewController.h"


@interface NewsViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate, NewsCollectionViewCellDelegate>

@property (nonatomic, retain) UICollectionView *collectV;
@property (nonatomic, retain) UIScrollView *scrollV;
@property (nonatomic, retain) UIButton *allButton; /**< 下拉菜单按钮 */
@property (nonatomic, copy) NSString *imageName; /**< 下拉菜单按钮图案 */
@property (nonatomic, retain) UIView *auxiliaryV;/**< 辅助跟随条 */
@property (nonatomic, retain) UIView *titleV; /**< 下拉菜单界面 */
@property (nonatomic, retain) NSMutableArray *pageCountArr;/**< 新闻数组 */
@property (nonatomic, assign) NSInteger page; /**< 页码 */
@property (nonatomic, retain) NSArray *jsonArray;
@property (nonatomic, retain) WJYNewsCollectionViewCell *newsCollectionViewCell;
@property (nonatomic, retain) NSString *number;

@property (nonatomic, assign)CGFloat ret; /**< 当前按钮数数组 */
@property (nonatomic, retain) NSMutableArray *newsArr;

@end

@implementation NewsViewController

#pragma mark - 将要出现的时候触发方法
- (void)viewWillAppear:(BOOL)animated {
    
    self.tabBarController.tabBar.hidden = NO;
    self.navigationController.navigationBar.hidden = NO;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.newsArr = [NSMutableArray array];

    self.pageCountArr = [NSMutableArray array];
    
#pragma mark - 网易title图片
    UIImageView *titleView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 45 , 22 )];
    titleView.image = [UIImage imageNamed:@"navbar_netease@2x"];
    self.navigationItem.titleView = titleView;
    
#pragma mark - 网易左边按钮
    UIImage *leftImage = [UIImage imageNamed:@"top_navi_bell_highlight@2x"];
    leftImage = [leftImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:leftImage style:UIBarButtonItemStyleDone target:self action:@selector(leftAction:)];
#pragma mark - 网易右边搜索按钮
//    UIImage *rightImage = [UIImage imageNamed:@""];
//    rightImage = [rightImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:leftImage style:UIBarButtonItemStyleDone target:self action:@selector(rightAction:)];
    
    // 控制留白以及坐标问题
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    // 初始化页书
    self.page = 0;
    
    // 申请数据
    [self handleData];
    
    // 创建滑动条
    [self createScrollView];
    
    // 创建下拉菜单
    [self createAllButton];
    
    // 创建Collectview
    [self createCollectView];
    

    
}




#pragma mark --- 24button的点击方法
- (void)leftAction:(UIButton *)btn
{
    WZXButtonViewController *buttonVC = [[WZXButtonViewController alloc] init];
    [self.navigationController pushViewController:buttonVC animated:YES];
}

#pragma mark --- 搜索的点击方法
- (void)rightAction:(UIButton *)btn{
//    WJYSearchViewController *search = [[WJYSearchViewController alloc]init];
//    [self.navigationController pushViewController:search animated:YES];
    WJYSearchViewController *newsSearchVC = [[WJYSearchViewController alloc] init];
    
    UINavigationController *navigationC = [[UINavigationController alloc] initWithRootViewController:newsSearchVC];
    
    navigationC.navigationBarHidden = NO;
    
    
    [self presentViewController:navigationC animated:YES completion:^{
    }];

}


#pragma mark --- 创建滑动条
- (void)createScrollView
{
    // 标题数组
    NSArray *array = [NSArray arrayWithObjects:@"头条", @"娱乐", @"体育", @"科技", @"轻松一刻", @"原创", @"旅游", @"时尚", nil];
    
    // 滑动条初始化
    self.scrollV = [[UIScrollView alloc]init];
    
    [self.view addSubview:self.scrollV];
    
    [self.scrollV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.top.equalTo(self.view);
        make.width.equalTo(self.view.mas_width).offset(-40);
        make.height.mas_equalTo(30);
        
    }];
    // 隐藏滚动条
    self.scrollV.showsHorizontalScrollIndicator = NO;
    self.scrollV.showsVerticalScrollIndicator = NO;
    // 遇到边框是否反弹
    self.scrollV.bounces = NO;
    // 偏移量
    self.scrollV.contentSize = CGSizeMake(NEWS_TITLE_WIDTH * 8, 0);
    // 协议
    self.scrollV.delegate = self;
    // 逐个创建按钮
    for (NSInteger i = 0; i < array.count; i++) {
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        
        // 根据数组设置Button文字及颜色
        [button setTitle:[array objectAtIndex:i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        // Button方法
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        
        // Button tag值
        button.tag = 3000 + i;
        
        //初始button为红色 大字体
        if (0 == i) {
            
            [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:20 ];
        } else {
            
            button.titleLabel.font = [UIFont systemFontOfSize:17 ];
        }
        
        // 讲按钮添加到滑动条上
        [self.scrollV addSubview:button];
        
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.mas_equalTo(NEWS_TITLE_WIDTH * i);
            make.top.mas_equalTo(-3);
            make.width.mas_equalTo(NEWS_TITLE_WIDTH);
            make.height.mas_equalTo(NEWS_SCROLL_HEIGHT);
            
        }];
        
    }
    
}



#pragma mark --- 创建CollectionView
- (void)createCollectView
{
    // collectionView子方法
    UICollectionViewFlowLayout *flowL = [[UICollectionViewFlowLayout alloc] init] ;
    
    // 滚动方向
    flowL.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowL.itemSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height - 49 - NEWS_SCROLL_HEIGHT - 64);
    
    // 左右间距为0
    flowL.minimumLineSpacing = 0;
    
    // CollectionView方法
    self.collectV = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.scrollV.frame.origin.y + self.scrollV.frame.size.height + 40, self.view.frame.size.width, self.view.frame.size.height - self.scrollV.frame.size.height - 64 - 49) collectionViewLayout:flowL];
    
    
    [self.view addSubview:self.collectV];
    [self.collectV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.scrollV.mas_bottom);
        
    }];
    
    
    // tag值
    self.collectV.tag = 2001;
    
    // 允许滑动
    self.collectV.pagingEnabled = YES;
    
    // 背景颜色
    self.collectV.backgroundColor = [UIColor whiteColor];//[UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:1.0];
    
    // 隐藏滚动条
    self.collectV.showsHorizontalScrollIndicator = NO;
    self.collectV.showsVerticalScrollIndicator = NO;
    
    // 不允许边界反弹
    self.collectV.bounces = NO;
    
    // 代理
    self.collectV.delegate = self;
    self.collectV.dataSource = self;
    
    // 注册cell
    [self.collectV registerClass:[WJYNewsCollectionViewCell class] forCellWithReuseIdentifier:@"WJYNewsCollectionViewCell"];
    [self.view addSubview:self.collectV];
}





#pragma mark --- 创建下拉菜单按钮
- (void)createAllButton
{
    
    self.allButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    // 添加
    [self.view addSubview:self.allButton];
    [self.allButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.scrollV.mas_right);
        make.top.equalTo(self.scrollV);
        make.right.equalTo(self.view);
        make.height.equalTo(self.scrollV);
        
    }];
    
    
    [self.allButton addTarget:self action:@selector(allButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.allButton setImage:[UIImage imageNamed:@"comment_arrow_down@2x.png"] forState:UIControlStateNormal];
    
    
    self.imageName = @"comment_arrow_down";
    
    
    
    
    
}

#pragma mark --- 下拉按钮方法
- (void)allButtonAction:(UIButton *)sender
{
    
    NSLog(@"下拉按钮方法,待完善!!!");
    
}

#pragma mark- 标题下拉菜单界面
- (void)createTitleView
{
    
    // 初始化
    self.titleV = [[UIView alloc] initWithFrame:CGRectMake(0, 64 + 40, SCREEN_FRAME.size.width, SCREEN_FRAME.size.height- 64 - 49)];
    
    // 背景颜色
    self.titleV.backgroundColor = [UIColor whiteColor];
    
    // 添加
    [self.view addSubview:self.titleV];
    
    
    // 将collectView放在上层
    [self.view bringSubviewToFront:self.collectV];
    
}

#pragma mark --- 按钮触发方法
- (void)buttonAction:(UIButton *)sender
{
    // 获取当前按钮数
    self.ret = sender.tag - 3000;
    
    // 滑动collectV 辅助滑动条的偏移量
    CGRect rect = CGRectMake(NEWS_TITLE_WIDTH * self.ret, NEWS_SCROLL_HEIGHT - 5, NEWS_TITLE_WIDTH, 5);
    
    // 辅助条滚动
    [self auxiliaryVMoveToPosition:rect];
    
    // collectV偏移
    CGFloat collectRet = (sender.tag - 3000) * self.view.frame.size.width;
    self.collectV.contentOffset = CGPointMake(collectRet, 0);
    
    
    // 点击Button颜色变黑
    for (NSInteger i = 0 ; i < 8; i++) {
        // 判断是否与相应按钮相等 改变颜色
        if (i != sender.tag - 3000) {
            UIButton *button = [self.scrollV.subviews objectAtIndex:i];
            [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:17 ];
        } else {
            UIButton *button = [self.scrollV.subviews objectAtIndex:i];
            [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:20];
        }
    }
    
}



#pragma mark- 减速结束的时候
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // 在减速结束的方法里判断偏移量
    if (scrollView == self.collectV) {
        
        // 获取当前页数
        NSInteger page = self.collectV.contentOffset.x / self.collectV.frame.size.width;
        
        
        // 滑动到相应的Button颜色变红
        for (NSInteger i = 0 ; i < 8; i++) {
            
            // 如果不是当前页面,设为初始颜色
            if (i != page) {
                UIButton *button = [self.scrollV.subviews objectAtIndex:i];
                [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                button.titleLabel.font = [UIFont systemFontOfSize:17];
                
                // 如果是当前页面,设置红色放大
            } else {
                UIButton *button = [self.scrollV.subviews objectAtIndex:i];
                [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
                button.titleLabel.font = [UIFont systemFontOfSize:20];
            }
        }
        
        // 计算偏移量
        CGPoint point = CGPointMake(page * NEWS_TITLE_WIDTH - (self.scrollV.frame.size.width - NEWS_TITLE_WIDTH) / 2.0 - 20.0, 0);
        
        // 判断
        if (point.x < 0) {
            point.x = 0;
        } else if (point.x + self.scrollV.frame.size.width > self.scrollV.contentSize.width) {
            point.x = self.scrollV.contentSize.width - self.scrollV.frame.size.width;
        }
        // 偏移
        [self.scrollV setContentOffset:point animated:YES];
        
    }
    
}

#pragma mark- 辅助条跟随动画
- (void) auxiliaryVMoveToPosition:(CGRect)position
{
    // 动画效果
    [UIView animateWithDuration:0.15f animations:^{
        self.auxiliaryV.frame = position;
        
    }];
    
}

#pragma mark- 监听:当collection 或着 scrollV 滑动 触发
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (2001 == scrollView.tag) {
        
        // 获取偏移量
        CGFloat ret = scrollView.contentOffset.x / [[UIScreen mainScreen] bounds].size.width;
        
        // 滑动collectV 辅助条的偏移量
        CGRect rect = CGRectMake(NEWS_TITLE_WIDTH * ret, NEWS_SCROLL_HEIGHT - 5, NEWS_TITLE_WIDTH, 5);
        
        // scrollV 偏移
        [self auxiliaryVMoveToPosition:rect];
        
        
    }
}

#pragma mark- 解析数据
- (void)handleData
{
    // 先获取json文件
    NSString *hpJsonPath = [[NSBundle mainBundle] pathForResource:@"HomePage" ofType:@"json"];
    
    // 这个json文件存放的是字符串, 转成data
    NSData *data = [NSData dataWithContentsOfFile:hpJsonPath];
    
    // 格式化成NSArray
    self.jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    
    // 遍历数组, 拿到参数去网络请求
    for (NSDictionary *dic in self.jsonArray) {
        
        // 先只所有的数据
        [self getDataFromNet:dic[@"URL"] key:dic[@"dicKey"] type:dic[@"type"]];
        
    }
    
}

#pragma mark- 封装不同参数的网络请求
- (void)getDataFromNet:(NSString *)url key:(NSString *)key type:(NSString *)type
{
    
    [AppTools getDataWithURL:url Block:^(id result) {
        
        
        NSMutableArray *arrM = [NSMutableArray array];
        
        for (NSDictionary *dic in result[key]) {
            WJYNewsModel *newsM = [[WJYNewsModel alloc] initWithDictionary:dic];
            
            [arrM addObject:newsM];
            
        }
        
        // 存放对应类型的小数组内容
        NSDictionary *dic = @{@"type":type, @"array":arrM};
        [self.pageCountArr addObject:dic];
        
        [self.collectV reloadData];
        
    } ErrorBlock:^(NSError *error) {
        
        NSLog(@"Error:%@", error);
        
    }];
    
    
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.pageCountArr.count;
}

#pragma mark CollectionViewCell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    self.newsCollectionViewCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WJYNewsCollectionViewCell" forIndexPath:indexPath];
    
    
    self.newsCollectionViewCell.newsCollectionViewCelldelegate = self;
    self.newsCollectionViewCell.pageCountArr = self.pageCountArr;
    
    self.newsCollectionViewCell.tableV.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh)];
    
    //下拉刷新
    self.newsCollectionViewCell.tableV.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewHeaderRefresh)];

    
    for (NSDictionary *dic in self.pageCountArr) {
        NSString *type = [dic objectForKey:@"type"];
        if ([type isEqualToString:[NSString stringWithFormat:@"%ld", indexPath.row]]) {
            NSMutableArray *smallArray = dic[@"array"];
            self.newsCollectionViewCell.tableViewArr = smallArray;
            [self.newsCollectionViewCell.tableV reloadData];
        }
    }
    
    return self.newsCollectionViewCell;
    
    
}

- (void)didSelectWithItem:(WJYNewsModel *)item type:(NSString *)type{

    
    if ([type isEqualToString:@"normal"] || [type isEqualToString:@"big"]) {
        
        WJYWebViewController *web = [[WJYWebViewController alloc]init];
        web.url = item.url_3w;
        web.docId = item.docid;
        [self.navigationController pushViewController:web animated:YES];

    }
    if ([type isEqualToString:@"photos"]) {

        WJYPhotosViewController *photos = [[WJYPhotosViewController alloc]init];
        photos.photosetID = item.photosetID;
        photos.photoTitle = item.title;
        [self.navigationController pushViewController:photos animated:YES];

    }
    
}

- (void)sendMessage:(NSString *)message arr:(NSMutableArray *)arr{
    WJYPhotosViewController *photos = [[WJYPhotosViewController alloc]init];
    photos.photosetID = arr[0];
    photos.photoTitle = arr[1];
    [self.navigationController pushViewController:photos animated:YES];
    
}

#pragma mark- 加载方法
- (void)tableViewRefresh
{
    // 获取当前页数
    NSInteger item = self.collectV.contentOffset.x / self.collectV.frame.size.width;
    
    // 获取区数 只有一个区
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:item inSection:0];
    
    // 取出数据
    NSDictionary *dic = [NSDictionary dictionaryWithDictionary:[self.jsonArray objectAtIndex:indexPath.item]];
    
    // 获取cell
    WJYNewsCollectionViewCell *cell = (WJYNewsCollectionViewCell *)[self.collectV cellForItemAtIndexPath:indexPath];
    
    // cell页数＋1
    cell.pageCount++;
    
    // 获取字符串
    NSString *string = [dic valueForKey:@"URL"];
    
    // 拼接字符串
    NSRange range = [string rangeOfString:@"0-20.html"];
    NSString *finalStr = [string stringByReplacingCharactersInRange:range withString:[NSString stringWithFormat:@"%ld-20.html", cell.pageCount * 20]];
    
    // 刷新响应的数据
    [self refreshDataFromNet:finalStr key:dic[@"dicKey"] type:dic[@"type"]];
    
}

#pragma mark- 刷新响应的数据
- (void)refreshDataFromNet:(NSString *)url key:(NSString *)key type:(NSString *)type
{
    [AppTools getDataWithURL:url Block:^(id result) {
        
        NSDictionary *dataDic = (NSDictionary *)result;
        
        NSArray *tArray = [dataDic objectForKey:key];
        
        for (NSDictionary *dic in self.pageCountArr) {
            
            if ([dic[@"type"] isEqualToString:type]) {
                
                NSMutableArray *arrM = [dic valueForKey:@"array"];
                
                for (NSDictionary *dic in tArray) {
                    WJYNewsModel *newsM = [[WJYNewsModel alloc] initWithDictionary:dic];
                    [arrM addObject:newsM];
                    
                }
                
            }
            
        }
        
        [self.collectV reloadData];
        
    } ErrorBlock:^(NSError *error) {
        
        
    }];
    

}

#pragma mark- 下拉刷新
- (void)tableViewHeaderRefresh
{
    
    [self handleData];
    [self.newsCollectionViewCell.tableV.mj_header endRefreshing];

    
    


}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
